package com.dfl.launcher;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;

import com.dfl.api.app.guistore.ISkinService;

public class MainActivity extends AppCompatActivity {
    private final MutableLiveData<ISkinService> service = new MutableLiveData<>(null);
    private final ClientImpl client = new ClientImpl();

    private final ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            service.postValue(ISkinService.Stub.asInterface(binder));
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service.postValue(null);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView tvState = findViewById(R.id.tvState);
        service.observe(this, service ->
                tvState.setText(service == null ? "未连接" : "已连接")
        );

        findViewById(R.id.btnConnect).setOnClickListener(v -> {
            ComponentName componentName = new ComponentName(
                    "com.dfl.guistore",
                    "com.dfl.guistore.service.SkinService"
            );
            Intent intent = new Intent();
            intent.setComponent(componentName);
            Log.d("ChangeSkin[client]", "bindService");
            final boolean result = bindService(intent, conn, Context.BIND_AUTO_CREATE);
            Log.d("ChangeSkin[client]", "bindService result : " + result);
        });

        service.observe(this, service -> {
            if (service == null) return;
            try {
                Log.d("ChangeSkin[client]", "registerSkinCallback");
                service.registerSkinCallback(client);
                // 注册成功后, 服务端会在五秒后发送一次换肤消息
            } catch (RemoteException e) {
                Log.e("ChangeSkin[client]", "registerSkinCallback failure", e);
            }
        });
    }
}